<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '商品评论',
    backgroundColor: '#f5f5f5',
    enablePullDownRefresh: true,
  },
}
</route>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import { getCommentPage, getCommentTags } from '@/service/goods/comment/comment'
import type { GoodsCommentVO, GoodsCommentTagItem } from '@/service/goods/comment/comment.d'

// 商品ID参数
const goodsId = ref<number>(0)

// 排序选项
const sortOptions = reactive([
  { value: 'createTime', text: '最新' },
  { value: 'score', text: '好评优先' },
])

// 筛选参数
const filterParams = reactive({
  current: 1,
  size: 10,
  sortOrder: undefined as 'createTime' | 'score' | undefined,
  tagIds: undefined,
})

// 数据状态
const commentList = ref<GoodsCommentVO[]>([])
const tags = ref<GoodsCommentTagItem[]>([])
const activeTag = ref<number>(0)
const activeSort = ref<number>(0)
const loadStatus = ref<'more' | 'loading' | 'noMore'>('more')
const isRefreshing = ref(false)

// 初始化加载
const loadData = async (isRefresh = false) => {
  try {
    loadStatus.value = 'loading'

    const res = await getCommentPage(
      filterParams.current,
      filterParams.size,
      goodsId.value,
      filterParams.sortOrder,
      filterParams.tagIds ? filterParams.tagIds : undefined,
    )
    console.log(filterParams.tagIds)

    if (isRefresh) {
      commentList.value = res.data.records
    } else {
      commentList.value.push(...res.data.records)
    }

    // 判断是否还有更多数据
    loadStatus.value = res.data.current < res.data.total ? 'more' : 'noMore'
    filterParams.current = res.data.current + 1
  } catch (error) {
    console.error('加载评论失败', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loadStatus.value = 'more'
    isRefreshing.value = false
    uni.stopPullDownRefresh()
  }
}

// 加载标签数据
const loadTags = async () => {
  try {
    const res = await getCommentTags(goodsId.value)
    tags.value = res.data.tags
    // 插入全部标签选项
    tags.value.unshift({
      id: 0,
      tagName: '全部',
      useCount: 0,
    })
  } catch (error) {
    console.error('加载标签失败', error)
  }
}

// 页面初始化
onLoad((options: any) => {
  goodsId.value = Number(options.goodsId)
  loadData()
  loadTags()
})

// 触底加载
const loadMore = () => {
  if (loadStatus.value === 'noMore') return
  loadData()
}

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true
  filterParams.current = 1
  loadData(true)
}

// 切换排序方式
const handleSortChange = (e: any) => {
  activeSort.value = e.detail.value
  filterParams.sortOrder = sortOptions[activeSort.value].value as 'createTime' | 'score'
  filterParams.current = 1
  loadData(true)
}

// 切换标签筛选
const toggleTag = (tagId: number) => {
  activeTag.value = tagId
  filterParams.tagIds = tagId === 0 ? undefined : tagId
  filterParams.current = 1
  loadData(true)
}

// 工具方法
const formatTime = (time?: string) => dayjs(time).format('YYYY-MM-DD HH:mm')

const getImageList = (urls: string) => urls.split(',')

const previewImage = (current: string) => {
  uni.previewImage({
    current,
    urls: getImageList(current),
  })
}
</script>
<template>
  <view class="comment-page">
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <picker :range="sortOptions" range-key="text" @change="handleSortChange">
        <view class="filter-item">
          {{ sortOptions[activeSort].text }}
        </view>
      </picker>

      <scroll-view scroll-x class="tag-scroll">
        <view
          v-for="tag in tags"
          :key="tag.id"
          class="tag-item"
          :class="{ active: activeTag === tag.id }"
          @click="toggleTag(tag.id)"
        >
          {{ tag.tagName }}
          <text v-if="tag.useCount > 0">({{ tag.useCount }})</text>
        </view>
      </scroll-view>
    </view>

    <!-- 评论列表 -->
    <scroll-view
      scroll-y
      class="comment-list"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 刷新提示 -->
      <view v-if="isRefreshing" class="refresh-tip">
        <uni-load-more status="loading" />
      </view>

      <!-- 评论项 -->
      <view v-for="comment in commentList" :key="comment.id" class="comment-item">
        <view class="user-info">
          <image :src="comment.avatarUrl" class="avatar" mode="aspectFill" />
          <view class="info-right">
            <text class="nickname">{{ comment.nickname }}</text>
            <uni-rate :value="comment.score" readonly size="12" class="rate-star" />
          </view>
          <text class="time">{{ formatTime(comment.createTime) }}</text>
        </view>

        <view class="content-box">
          <text class="content">{{ comment.content }}</text>
          <view v-if="comment.tagNames?.length" class="tags">
            <text v-for="(tag, index) in comment.tagNames" :key="index" class="tag">
              {{ tag }}
            </text>
          </view>
        </view>

        <!-- 图片预览 -->
        <scroll-view v-if="comment.contentUrl" scroll-x class="image-scroll">
          <image
            v-for="(img, idx) in getImageList(comment.contentUrl)"
            :key="idx"
            :src="img"
            mode="aspectFill"
            class="preview-image"
            @click="previewImage(img)"
          />
        </scroll-view>
      </view>

      <!-- 加载状态提示 -->
      <uni-load-more
        :status="loadStatus"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多了',
        }"
      />
    </scroll-view>
  </view>
</template>
<style lang="scss" scoped>
.comment-page {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .filter-bar {
    display: flex;
    padding: 20rpx;
    background: #fff;
    border-bottom: 1rpx solid #eee;
    .filter-item {
      display: inline-flex;
      align-items: center;
      padding: 10rpx 20rpx;
      margin-right: 20rpx;
      font-size: 26rpx;
      background: #f5f5f5;
      border-radius: 40rpx;
    }

    .tag-scroll {
      white-space: nowrap;

      .tag-item {
        display: inline-block;
        padding: 8rpx;
        margin-right: 20rpx;
        font-size: 20rpx;
        color: #666;
        background: #f5f5f5;
        border-radius: 40rpx;

        &.active {
          color: white;
          background: linear-gradient(90deg, $uni-bg-themes-abate, $uni-bg-themes);
        }
      }
    }
  }

  .comment-list {
    flex: 1;

    .refresh-tip {
      padding: 20rpx;
      text-align: center;
    }

    .comment-item {
      padding: 20rpx;
      margin: 10rpx;
      margin-bottom: 20rpx;
      background: #fff;
      border-radius: 16rpx;

      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .avatar {
          width: 60rpx;
          height: 60rpx;
          margin-right: 20rpx;
          border-radius: 50%;
        }

        .info-right {
          flex: 1;

          .nickname {
            font-size: 28rpx;
            color: #333;
          }

          .rate-star {
            margin-top: 8rpx;
          }
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .content-box {
        .content {
          font-size: 24rpx;
          line-height: 1.6;
          color: #333;
        }

        .tags {
          margin-top: 20rpx;

          .tag {
            display: inline-block;
            padding: 6rpx 16rpx;
            margin-right: 16rpx;
            font-size: 24rpx;
            color: #666;
            background: #f5f5f5;
            border-radius: 8rpx;
          }
        }
      }

      .image-scroll {
        margin-top: 20rpx;
        white-space: nowrap;

        .preview-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 20rpx;
          border: 1rpx solid #eee;
          border-radius: 8rpx;
        }
      }
    }
  }
}
</style>
